import sys
import queue
import time
import os
from threading import Thread, Lock


class PrintOut:
    _instance_lock = Lock()

    def __init__(self, path):
        self.file_path = path
        self.content = queue.Queue()
        self.old_print = sys.stdout
        self.exec = True
        self.create_dir()
        self.write("process id: " + str(os.getpid()))
        self.print_thr = Thread(target=self.print_val)
        self.print_thr.start()

    def stop(self):
        self.exec = False

    def create_dir(self):
        if not os.path.exists(self.file_path):
            os.makedirs(self.file_path)

    def write_str(self):
        PrintOut._instance_lock.acquire()
        file_name = time.strftime("%Y-%m-%d", time.localtime()) + ".log"
        with open(self.file_path + file_name, "a+") as fp:
            while not self.content.empty():
                write_str = self.content.get()
                fp.write(write_str)
                fp.flush()
        PrintOut._instance_lock.release()

    def print_val(self):
        while self.exec:
            if not self.content.empty():
                self.write_str()
                time.sleep(1)

    def write(self, arg):
        str_val = arg.strip()
        if len(str_val) > 0:
            write_str = time.strftime("%Y-%m-%d %H:%M:%S ", time.localtime()) + str_val + "\n"
            self.old_print.write(write_str)
            self.content.put(write_str)

    def flush(self):
        self.old_print.flush()
        self.write_str()


sys.stdout = PrintOut(path="../cache/log/")
